package com.example.himalaya.view.fragments;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import com.example.himalaya.R;
import com.example.himalaya.view.activity.DownloadedMusicActivity;
import com.example.himalaya.view.activity.LoveSongViewActivity;
import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.base.BaseFragment;
import com.example.himalaya.view_component.UILoader;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;

import java.text.SimpleDateFormat;

public class MyPageFragment extends BaseFragment {

    // Constance
    private static int DEFAULT_MAX_CLOSE_TIME = 60;
    private static int STOP_CLOSE_MUSIC_CODE = 0;
    private static int STOP_AFTER_CURRENT_MUSIC = -1;

    // Format Tool
    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat mMinFormat = new SimpleDateFormat("mm:ss");


    // Other UI Obejct
    private UILoader mUiLoader = null;

    // UI Object
    private View mSuccessView;
    private Switch mSwitchOfMusic;
    private SeekBar mSeekBarOfCloseMusic;
    private int mMusicCloseTime = 0;
    private TextView mTimeTv;

    // Flag
    private boolean mFlagOfCloseMusic;
    private CountDownTimer mTimer;
    private LinearLayout mLoadedBtn;
    private LinearLayout mLovedBtn;
    private Context mContext;

    @Override
    protected View onSubViewLoaded(final LayoutInflater inflater, ViewGroup container) {

        initVariable();

        if (mUiLoader == null) {
            mUiLoader = new UILoader(container.getContext()) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSuccessView(inflater, container);
                }

            };

            if (mUiLoader.getParent() instanceof ViewGroup) {
                ((ViewGroup) mUiLoader.getParent()).removeView(mUiLoader);
            }

        }

        mUiLoader.updateStatus(UILoader.UIStatus.SUCCESS);

        return mUiLoader;
    }

    private void initVariable() {
        mContext = BaseApplication.getAppContext();
    }

    private View createSuccessView(LayoutInflater inflater, ViewGroup container) {

        if (mSuccessView != null) {
            return mSuccessView;
        }
        mSuccessView = inflater.inflate(R.layout.fragment_my, container, false);


        initSuccessVariable();
        initSuccessView();
        initSuccessListener();
        return mSuccessView;
    }

    private void initSuccessVariable() {
        mSwitchOfMusic = mSuccessView.findViewById(R.id.switch_of_music);

        mSeekBarOfCloseMusic = mSuccessView.findViewById(R.id.music_close_seek_bar);

        mTimeTv = mSuccessView.findViewById(R.id.time_tv);

        mLovedBtn = mSuccessView.findViewById(R.id.my_loved_btn);
        mLoadedBtn = mSuccessView.findViewById(R.id.my_downed_btn);
    }

    private void initSuccessListener() {
        // 已下载部分的点击监听
        mLovedBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 跳转到我喜欢的界面
                // Toast.makeText(BaseApplication.getAppContext(), "跳转到我喜欢的界面", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(mContext, LoveSongViewActivity.class);

                startActivity(intent);
            }
        });

        // 已下载部分的点击监听
        mLoadedBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 跳转到已下载的界面
                // Toast.makeText(BaseApplication.getAppContext(), "跳转到已下载的界面", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(mContext, DownloadedMusicActivity.class);

                startActivity(intent);
            }
        });


        // 开启或者关闭定时停止播放开关的监听
        mSwitchOfMusic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean ifOpen) {
                // (System.currentTimeMillis() + 10000 表示在10秒之后停止播放)

                if (ifOpen) {
                    handleCloseMusic();

                    mFlagOfCloseMusic = true;
                } else {
                    XmPlayerManager.getInstance(BaseApplication.getAppContext()).pausePlayInMillis(STOP_CLOSE_MUSIC_CODE);

                    mTimeTv.setText(getResources().getString(R.string.default_mm_ss));

                    if (mTimer != null) {
                        mTimer.cancel();
                    }
                    mFlagOfCloseMusic = false;

                }
            }
        });

        // 拖动进度条的监听
        mSeekBarOfCloseMusic.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean isFormUser) {


                mMusicCloseTime = progress * 1000 * 60;

                String string = mMinFormat.format((progress * 1000 * 60));

                mTimeTv.setText(string);

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mFlagOfCloseMusic) {
                    handleCloseMusic();
                }
            }
        });
    }

    private void handleCloseMusic() {
        XmPlayerManager.getInstance(BaseApplication.getAppContext()).pausePlayInMillis(mMusicCloseTime + System.currentTimeMillis());

        if (mTimer != null) {
            mTimer.cancel();
        }

        mTimer = new CountDownTimer(mMusicCloseTime, 1000) {
            @Override
            public void onTick(long remainingTime) {

                String string = mMinFormat.format(remainingTime);

                mTimeTv.setText(string);

                mSeekBarOfCloseMusic.setProgress((int) (remainingTime / 1000 / 60));
            }

            @Override
            public void onFinish() {
                mTimer.cancel();
                mTimer = null;
            }
        };

        mTimer.start();
    }

    private void initSuccessView() {

        // 设置定时停止听歌的最大值
        mSeekBarOfCloseMusic.setMax(DEFAULT_MAX_CLOSE_TIME);
    }
}
